package com.example.front.main.shop;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.front.MyApplication;
import com.example.front.R;
import com.example.front.main.home.PsGameActivity;
import com.example.front.sign.LoginActivity;
import com.example.front.utils.MyAdapter;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ShoppingCartActivity extends AppCompatActivity {
    private String URL;
    private MyApplication myApplication;
    private ListView product_listView;
    private MyAdapter<SelectProduct> productMyAdapter = null;
    private List<SelectProduct> productList = null;
    private List<SelectProduct> selectProducts = null;
//    private Button time_button;
//    private Button date_button;
//    private TextView time_textView;
//    private TextView date_textView;
    private EditText room_editText;
    private int hour;
    private int minute;
    private int year;
    private int month;
    private int day;
    private String jsonString;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);
        product_listView = findViewById(R.id.product_listView);
//        time_button = findViewById(R.id.time_button);
//        date_button = findViewById(R.id.date_button);
//        time_textView = findViewById(R.id.time_textView);
//        date_textView = findViewById(R.id.date_textView);
        room_editText = findViewById(R.id.room_editText);
        myApplication = (MyApplication)getApplication();
        URL = myApplication.getURL();
        productList = (ArrayList<SelectProduct>)getIntent().getSerializableExtra("productList");
        selectProducts = new ArrayList<SelectProduct>();
        for (int i = 0; i < productList.size(); i++){
            SelectProduct selectProduct = productList.get(i);
            if(selectProduct.getNumber() != 0){
                selectProducts.add(selectProduct);
                System.out.println("已添加" + selectProduct.getName());
            }
        }
        JSONArray jsonArray = new JSONArray();
        for(int i  = 0; i < selectProducts.size(); i++){
            JSONObject object = new JSONObject();
            try {
                object.put("id", selectProducts.get(i).getId());
                object.put("price", selectProducts.get(i).getPrice());
                object.put("number", selectProducts.get(i).getNumber());
                object.put("photo", selectProducts.get(i).getPhoto());
                jsonArray.put(object);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
        jsonString = jsonArray.toString();
        productMyAdapter = new MyAdapter<SelectProduct>((ArrayList) selectProducts, R.layout.cart_product_list_item) {
            @Override
            public void bindView(ViewHolder holder, SelectProduct obj) {
                imageView = holder.getView(R.id.product_image);
                Glide.with(ShoppingCartActivity.this)
                        .load(obj.getPhoto())
                        .error(R.drawable.error)
                        .crossFade()
                        .into(imageView);
                holder.setText(R.id.name_textView, obj.getName() + "");
                holder.setText(R.id.type_textView, " " + obj.getType() + " " + obj.getPrice() + "/" + obj.getUnit());
                holder.setText(R.id.product_number_textView, "x " + obj.getNumber());
                holder.setText(R.id.product_total_textView, "￥" + obj.getNumber() * obj.getPrice());
            }
        };
        product_listView.setAdapter(productMyAdapter);
    }
//
//    public void getTime_onClick(View view){
//        Calendar calendar = Calendar.getInstance();
//        hour  = calendar.get(Calendar.HOUR_OF_DAY);    //得到小时
//        minute  = calendar.get(Calendar.MINUTE);            //得到分钟
//        new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
//            @Override
//            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
//                time_textView.setText(hour + ":" + minute);
//            }
//        }, hour, minute, true).show();
//    }
//
//    public void getDate_onClick(View view){
//        Calendar mcalendar = Calendar.getInstance();     //  获取当前时间    —   年、月、日
//        year = mcalendar.get(Calendar.YEAR);         //  得到当前年
//        month = mcalendar.get(Calendar.MONTH) + 1;       //  得到当前月
//        day = mcalendar.get(Calendar.DAY_OF_MONTH) + 1;  //  得到当前日
//
//        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {      //  日期选择对话框
//            @Override
//            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//                //  这个方法是得到选择后的 年，月，日，分别对应着三个参数 — year、month、dayOfMonth
//                date_textView.setText(year + "-" + month + "-" + day);
//            }
//        },year,month,day).show();   //  弹出日历对话框时，默认显示 年，月，日
//    }

    public void submit_onClick(View view){
//        String time = date_textView.getText().toString() + " " + time_textView.getText().toString() + ":00";
        SharedPreferences sharedPreferences = getSharedPreferences("Login", Context.MODE_PRIVATE);
        String account = sharedPreferences.getString("account", "");
        String room = room_editText.getText().toString();
        if(room.equals("")){
            Toast.makeText(ShoppingCartActivity.this, "请输入要送达的房号", Toast.LENGTH_SHORT).show();
        }
        else {
            OkHttpUtils
                    .post()
                    .url(URL + "/order/submitOrder")
                    .addParams("account", account)
                    .addParams("room", room)
//                .addParams("time", time)
                    .addParams("jsonString", jsonString)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Request request, Exception e) {
                        }
                        @Override
                        public void onResponse(String response) {
                            if(response.equals("true")) {
                                Toast.makeText(ShoppingCartActivity.this, "提交成功！", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(ShoppingCartActivity.this, ProductActivity.class);
                                startActivity(intent);
                                ProductActivity.the.recreate();
                                finish();
                            }
                            else
                                Toast.makeText(ShoppingCartActivity.this, "提交失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }
}
